package com.manor.paradise.dialog

import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.text.Editable
import android.text.Spannable
import android.text.Spannable.SPAN_INCLUSIVE_INCLUSIVE
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.AbsoluteSizeSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.AdapterView
import android.widget.EditText
import android.widget.GridView
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.manor.paradise.R
import com.manor.paradise.bean.MineInfoBean
import kotlinx.android.synthetic.main.dialog_input_password.*
import java.lang.reflect.Method
import java.util.*


/**
 * 用途：
 */
class LybInputPasswordDialog(val mOnInputEndListener: OnInputEndListener, val mJzInfoEntity: MineInfoBean) : BottomSheetDialogFragment(), View.OnClickListener{
    override fun onClick(v: View?) {
        when(v?.id){
            R.id.dialogCloseIv -> {
                dismiss()
            }
            R.id.dialogExchangeWithMlLayout -> {//选择米粒抵扣
                dialogExchangeWithMlLayout.isSelected = true
                dialogExchangeWithPowerLayout.isSelected = false
                mMlExchange = true
                setPrice(true)

            }
            R.id.dialogExchangeWithPowerLayout -> {//选择能量抵扣
                dialogExchangeWithPowerLayout.isSelected = true
                dialogExchangeWithMlLayout.isSelected = false
                mMlExchange = false
                setPrice(false)
            }
            R.id.dialogChangePasswordTv -> {
                ToastUtils.showShort("修改支付密码")
            }
        }
    }

    private var enterAnim: Animation? = null
    private var exitAnim: Animation? = null
    private var gridView: GridView? = null
    private var valueList: ArrayList<Map<String, String>>? = null
    private var mMlExchange = true//是否使用米粒兑换
    /**
     * 输入监听事件
     */
    private val textWatcher = object : TextWatcher {
        override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}

        override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}

        override fun afterTextChanged(s: Editable) {
            if(s.length == 6){
                mOnInputEndListener.end(s.toString(), mJzInfoEntity, mMlExchange)
                dismiss()
            }
        }
    }
    override fun onStart() {
        super.onStart()

        view?.post {
            val parent = view?.parent as View
            val params = parent.layoutParams as androidx.coordinatorlayout.widget.CoordinatorLayout.LayoutParams
            val behavior = params.behavior
            val bottomSheetBehavior = behavior as BottomSheetBehavior<*>
            bottomSheetBehavior.isHideable = false
            view?.measuredHeight?.let { bottomSheetBehavior.peekHeight = it }
//            parent.setBackgroundColor(Color.WHITE)
            parent.setBackgroundColor(Color.TRANSPARENT)
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme)
    }
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.dialog_input_password, container, false)
    }
    private fun setPrice(mlType: Boolean){
        val sp: Spannable = if (mlType){
            SpannableString("兑换 " + mJzInfoEntity.name + "需要消耗 " + mJzInfoEntity.price + "个米粒")
        }else{
            SpannableString("兑换 " + mJzInfoEntity.name + "需要消耗 " + mJzInfoEntity.price + "个能量")
        }

        val firstLength = ("兑换 " + mJzInfoEntity.name + "需要消耗 ").length
        val secondLength = (firstLength + mJzInfoEntity.price.toString().length)
        val finalLength = sp.length

        sp.setSpan(AbsoluteSizeSpan(12, true), 0, firstLength, SPAN_INCLUSIVE_INCLUSIVE)
        sp.setSpan(AbsoluteSizeSpan(16, true), firstLength, secondLength, SPAN_INCLUSIVE_INCLUSIVE)
        sp.setSpan(AbsoluteSizeSpan(12, true), secondLength, finalLength, SPAN_INCLUSIVE_INCLUSIVE)
        dialogJzNameTv.text = sp
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setPrice(true)
        dialogExchangeWithMlLayout.isSelected = true
        dialogChangePasswordTv.paint.flags = Paint.UNDERLINE_TEXT_FLAG
        dialogCloseIv.setOnClickListener(this)
        dialogExchangeWithMlLayout.setOnClickListener(this)
        dialogExchangeWithPowerLayout.setOnClickListener(this)
        dialogChangePasswordTv.setOnClickListener(this)
        payDialogPassWordEt.addTextChangedListener(textWatcher)
        enterAnim = AnimationUtils.loadAnimation(activity, R.anim.push_bottom_in)
        exitAnim = AnimationUtils.loadAnimation(activity, R.anim.push_bottom_out)

        // 设置不调用系统键盘
        activity?.window?.setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        try {
            val cls = EditText::class.java
            val setShowSoftInputOnFocus: Method
            setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", Boolean::class.javaPrimitiveType!!)
            setShowSoftInputOnFocus.isAccessible = true
            setShowSoftInputOnFocus.invoke(payDialogPassWordEt, false)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        valueList = payDialogBanKeyboardView.valueList
        gridView = payDialogBanKeyboardView.gridView
        gridView?.onItemClickListener = onItemClickListener

        payDialogPassWordEt.setOnClickListener {
            payDialogBanKeyboardView.isFocusable = true
            payDialogBanKeyboardView.isFocusableInTouchMode = true
            payDialogBanKeyboardView.startAnimation(enterAnim)
            payDialogBanKeyboardView.visibility = View.VISIBLE
        }

    }
    interface OnInputEndListener{
        fun end(password: String, entity: MineInfoBean, payType: Boolean)
    }
    private val onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
        if (position < 11 && position != 9) {    //点击0~9按钮

            var amount = payDialogPassWordEt.text.toString().trim { it <= ' ' }
            amount += valueList?.get(position)?.get("name")!!

            payDialogPassWordEt.setText(amount)

            val ea = payDialogPassWordEt.text
            ea?.length?.let { payDialogPassWordEt.setSelection(it) }
        } else {

            if (position == 9) {      //点击退格键
                var amount = payDialogPassWordEt.text.toString().trim { it <= ' ' }
                if (!amount.contains(".")) {
                    amount += valueList?.get(position)?.get("name")!!
                    payDialogPassWordEt.setText(amount)

                    val ea = payDialogPassWordEt.text
                    ea?.length?.let { payDialogPassWordEt.setSelection(it) }
                }
            }

            if (position == 11) {      //点击退格键
                var amount = payDialogPassWordEt.text.toString().trim { it <= ' ' }
                if (amount.isNotEmpty()) {
                    amount = amount.substring(0, amount.length - 1)
                    payDialogPassWordEt.setText(amount)

                    val ea = payDialogPassWordEt.text
                    ea?.length?.let { payDialogPassWordEt.setSelection(it) }
                }
            }
        }
    }
}
